using System.Text.Json;
using Microsoft.Extensions.Logging;

namespace SumerCoreDevOps.ExecuteNodeApi.Services;

/// <summary>
/// 节点配置持久化服务
/// </summary>
public class NodeConfigPersistenceService
{
    private readonly ILogger<NodeConfigPersistenceService> _logger;
    private readonly string _configFilePath;

    public NodeConfigPersistenceService(ILogger<NodeConfigPersistenceService> logger)
    {
        _logger = logger;
        _configFilePath = Path.Combine(AppContext.BaseDirectory, "node-config.json");
    }

    /// <summary>
    /// 保存节点配置
    /// </summary>
    public async Task SaveConfigAsync(NodeConfig config)
    {
        try
        {
            var json = JsonSerializer.Serialize(config, new JsonSerializerOptions
            {
                WriteIndented = true
            });

            await File.WriteAllTextAsync(_configFilePath, json);

            _logger.LogInformation("节点配置已保存到: {FilePath}", _configFilePath);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "保存节点配置失败");
            throw;
        }
    }

    /// <summary>
    /// 加载节点配置
    /// </summary>
    public async Task<NodeConfig?> LoadConfigAsync()
    {
        try
        {
            if (!File.Exists(_configFilePath))
            {
                _logger.LogInformation("节点配置文件不存在: {FilePath}", _configFilePath);
                return null;
            }

            var json = await File.ReadAllTextAsync(_configFilePath);
            var config = JsonSerializer.Deserialize<NodeConfig>(json);

            _logger.LogInformation("节点配置已加载: NodeId={NodeId}", config?.NodeId);

            return config;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "加载节点配置失败");
            return null;
        }
    }

    /// <summary>
    /// 删除节点配置
    /// </summary>
    public void DeleteConfig()
    {
        try
        {
            if (File.Exists(_configFilePath))
            {
                File.Delete(_configFilePath);
                _logger.LogInformation("节点配置已删除");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除节点配置失败");
        }
    }

    /// <summary>
    /// 更新服务器地址
    /// </summary>
    public async Task UpdateServerAddressAsync(string serverHost, int serverPort)
    {
        var config = await LoadConfigAsync();
        if (config != null)
        {
            config.ServerHost = serverHost;
            config.ServerPort = serverPort;
            await SaveConfigAsync(config);

            _logger.LogInformation("服务器地址已更新: {Host}:{Port}", serverHost, serverPort);
        }
    }
}

/// <summary>
/// 节点配置
/// </summary>
public class NodeConfig
{
    /// <summary>
    /// 节点ID
    /// </summary>
    public long NodeId { get; set; }

    /// <summary>
    /// 节点唯一标识
    /// </summary>
    public string NodeKey { get; set; } = null!;

    /// <summary>
    /// 节点名称
    /// </summary>
    public string NodeName { get; set; } = null!;

    /// <summary>
    /// 连接令牌（Connection Token）
    /// 持久化令牌，用于重连认证
    /// </summary>
    public string ConnectionToken { get; set; } = null!;

    /// <summary>
    /// 服务器地址
    /// </summary>
    public string ServerHost { get; set; } = null!;

    /// <summary>
    /// 服务器端口
    /// </summary>
    public int ServerPort { get; set; }

    /// <summary>
    /// 配置保存时间
    /// </summary>
    public DateTime SavedAt { get; set; }
}
